package com.zlp.boot1.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

/**
 * @Author: zhulaiping
 * @Date: 2021/11/1 12:02
 */
@WebServlet("/cookie1")
public class CookieDemo1 extends HttpServlet {

    int count = 0;
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/plain");
        PrintWriter writer = resp.getWriter();
        Cookie[] cookies = req.getCookies();
        if(cookies != null){
            for(Cookie cookie:cookies){
                writer.write("Cookie name: "+cookie.getName()+"\r\n");
                writer.write("Cookie value: "+cookie.getValue()+"\r\n");
                writer.write("Max Age: "+cookie.getMaxAge()+"\r\n");
                //设置为0后，在响应回去浏览器才会删除，设置成-1，cookie会存在当前浏览器的进程中，浏览器关闭cookie消失
                /*cookie.setMaxAge(0);
                resp.addCookie(cookie);*/
            }


        }else {
            writer.println("No cookie");
        }

        resp.addCookie(new Cookie("name"+count,"value"+count));
        count++;
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        doGet(req,resp);
    }
}
